package com.oa.crm.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.crm.entity.Customer;
import com.oa.crm.entity.CustomerBusiness;
import com.oa.crm.service.CustomerBusinessService;
import com.oa.crm.vo.CustomerBusinessAddVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/**/oa/crm/customerBusiness")
@Api(tags = {"crm_customer_business-操作接口"})
public class CustomerBusinessController {

    static Logger logger = LoggerFactory.getLogger(CustomerBusinessController.class);

    @Autowired
    private CustomerBusinessService customerBusinessService;

    @ApiOperation(value = "crm_customer_business-查询列表", notes = " ")
    @ApiEntityParams(CustomerBusiness.class)
    @ApiResponses({@ApiResponse(code = 200, response = CustomerBusiness.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listCustomerBusiness(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "businessIds");
        QueryWrapper<CustomerBusiness> qw = QueryTools.initQueryWrapper(CustomerBusiness.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = customerBusinessService.selectListMapByWhere(page, qw, params);

        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "crm_customer_business-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CustomerBusiness.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addCustomerBusiness(@RequestBody CustomerBusinessAddVo customerBusinessAddVo) {


        if (StringUtils.isEmpty(customerBusinessAddVo.getCustomerBusiness().getBusinessId())) {
            customerBusinessAddVo.getCustomerBusiness().setBusinessId(customerBusinessService.createKey("businessId"));
        } else {
            CustomerBusiness customerBusinessQuery = new CustomerBusiness(customerBusinessAddVo.getCustomerBusiness().getBusinessId());
            if (customerBusinessService.countByWhere(customerBusinessQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        customerBusinessService.insertCustomerBusiness(customerBusinessAddVo);

        return Result.ok("add-ok", "添加成功！").setData(customerBusinessAddVo);
    }

    @ApiOperation(value = "crm_customer_business-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delCustomerBusiness(@RequestBody CustomerBusiness customerBusiness) {

        customerBusinessService.removeById(customerBusiness);


        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "crm_customer_business-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CustomerBusiness.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editCustomerBusiness(@RequestBody CustomerBusinessAddVo customerBusinessAddVo) {


        customerBusinessService.updateCustomerBusiness(customerBusinessAddVo);

        return Result.ok("edit-ok", "修改成功！").setData(customerBusinessAddVo);
    }

    @ApiOperation(value = "设置客户的是否关注状态", notes = "addCustomer,主键如果为空，后台自动生成")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/isAttention", method = RequestMethod.POST)
    public Result isAttention(@RequestBody Map<String, Object> customerBusiness) {


        customerBusinessService.isAttention(customerBusiness);

        return Result.ok("query-ok", "");
    }

    @ApiOperation(value = "crm_customer_business-批量修改某些字段", notes = "")
    @ApiEntityParams(value = CustomerBusiness.class, props = {}, remark = "crm_customer_business", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = CustomerBusiness.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        customerBusinessService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "crm_customer_business-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelCustomerBusiness(@RequestBody List<CustomerBusiness> customerBusinesss) {
        User user = LoginUtils.getCurrentUserInfo();
        if (customerBusinesss.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<CustomerBusiness> datasDb = customerBusinessService.listByIds(customerBusinesss.stream().map(i -> i.getBusinessId()).collect(Collectors.toList()));

        List<CustomerBusiness> can = new ArrayList<>();
        List<CustomerBusiness> no = new ArrayList<>();
        for (CustomerBusiness data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            customerBusinessService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getBusinessId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "crm_customer_business-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CustomerBusiness.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(CustomerBusiness customerBusiness) {
        CustomerBusiness data = (CustomerBusiness) customerBusinessService.getById(customerBusiness);
        return Result.ok().setData(data);
    }

    @ApiOperation(value = "根据主键查询一条数据", notes = "getBusinessById")
    @RequestMapping(value = "/getBusinessById", method = RequestMethod.GET)
    public Result getBusinessById(@RequestParam Map<String, Object> customerBusinessMap) {

        CustomerBusiness result = null;

        CustomerBusiness customerBusiness = new CustomerBusiness();
        customerBusiness.setBusinessId((String) customerBusinessMap.get("businessId"));
        customerBusiness.setBranchId((String) customerBusinessMap.get("branchId"));
        result = customerBusinessService.selectOneObject(customerBusiness);

        return Result.ok().setData(result);
    }
}
